/**

 * @author zhaokai

 * @date 2019-10-30 21:26

 * @description the study of http module
 */

let http = require('http');

/*
* @func create serve
* */
let serve = http.createServer();
serve.timeout = 12000;//默认是两分钟

//connect listening
serve.on('connect',function (req,res) {
    res.end('connect succes')
});
//request listening
serve.on('request',function (req,res) {
    res.end('succes')
});
//close listening (调用serve.close()会触发)
serve.on('close',function (req,res) {
    res.end('close succes')
});
//此事件的监听器负责关闭或销毁底层套接字。
serve.on('clientError', (err, socket) => {
    socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
//serve listening
serve.listen(3000,'127.0.0.1', function () {
    console.log('serve is starting!');
});


/*
* @Client send request
* */
http.get('http://nodejs.cn/index.json', function (res) {
    console.log(res.statusCode)
});
http.request('http://nodejs.cn/index.json',function(res){
        console.log(`状态码: ${res.statusCode}`);

});

const request = http.request("http://127.0.0.1:3000",(responeMsg)=>{
    console.log(responeMsg.statusCode);
    console.log(responeMsg.statusMessage);
    responeMsg.on('connect',function(req){
        console.log('请求已发出')
    })
    responeMsg.on("data",(data)=>{
        console.log("data:",data.toString());
    })
});

request.method="GET";
request.on('connect', (res, socket, head) => {
    console.log('已连接');
});

request.end();

var options = {
    host: "localhost",
    port: 3000
}

var req = http.request(options);

req.on("connect",function(res, socket, head) {
    console.log("dddddddd");
});

req.end();
